module.exports = (function () {

	'use strict';

	var fs = require('fs'),
		http = require('http'),
		url = require('url'),
		path = require('path'),
		querystring = require('querystring'),
		requestAPI = require("./requstAPI.js");

	return { 

		start: function () {
			var port = this.config.port;
			var ip = this.config.ip;

			var httpServer = http.createServer(this.processRequest.bind(this));

			httpServer.listen(port, function () {
				console.log("[HttpServer][Starting]","running at http://"+ip+":"+port+"/");
				console.timeEnd("[HttpServer][Started]");
			});

			httpServer.on("error", function (error) {
				console.error(error);
			})
		},
		processRequest: function (request, response) {
			var has_ext = true;
			// 1.get pathname
			var request_url = url.parse(request.url);
			var path_name = request_url.pathname;
			var query_params = querystring.parse(request_url.query);
			if ( request_url.query != null && query_params.s != "") {
				console.log(query_params)
				requestAPI.request(query_params,request,response);
				return;
			}
			
			// 2.avoid chinese messy code
			path_name = decodeURI(path_name);

			// 3.if path_name has extention ?
			if (path.extname(path_name) === '') {

				if (path_name.charAt(path_name.length - 1) != "/") {
					path_name += "/";
					console.log("///")
					var redirect = "http://" + request.headers.host + path_name;
					response.writeHead(301, {
						location: redirect
					});
					response.end();
					return;
				}

				path_name += "index.html";
				has_ext = false;
			}

			var root_path = path.resolve('.');
			// total file_path
			var file_path = path.join(root_path, path_name);

			var content_type = this.getFileContentType(file_path);
			// 4.if file is exists ?
			fs.exists(file_path, function (exists) {
				if (exists) {
					if (content_type == "image/jpeg" || content_type == "image/png") {
						fs.readFile(file_path, "binary", function (err, data) {
							if (err) {
								console.log(err);
								return;
							}
							response.writeHead(200,{"content-type":content_type })
							response.write(data, "binary");
							response.end();
						})
						return;
					}
					response.writeHead(200, { "Content-Type": content_type });
					var read_stream = fs.createReadStream(file_path, "utf-8");
					read_stream.on("error",function () {
						response.writeHead(500, {"Content-Type": "text/html"});
						response.end("<h1>500 Server Error</h1>");
					});
					read_stream.pipe(response);
				}else {
					if (has_ext) {
						response.writeHead(404, { "Content-Type": "text/html" });
						response.end("<h1>404 Not Found</h1>");
					}else {
						var html_str = "<head><meta charset='utf-8'></head>";

						try {
							var file_dir = file_path.substring(0, file_path.lastIndexOf("\\"));
							var files = fs.readdirSync(file_dir);

							for(var i in files) {
								var filename = files[i];
								html_str += "<div><a  href='"+filename+"'>"+filename+"</a></div>";
							}

						} catch(e) {
							html_str += "<h1>您访问的目录不存在</h1>"
						}
						response.writeHead(200, {"Content-Type": "text/html"});
						response.end();
					}
				}
			});

		},
		getFileContentType: function (file_path) {
			var content_type = this.config.mime;
			var ext_str = path.extname(file_path).substr(1);

			if (content_type.hasOwnProperty(ext_str)) 
				return content_type[ext_str];
			else 
				return content_type.default;
		},
		config: {
			port: 8080,
			ip: '',
			mime: {
				html: "text/html",
				js: "text/javascript",
				css: "text/css",
				gif: "image/gif",
				jpg: "image/jpeg",
				png: "image/png",
				ico: "image/icon",
				txt: "text/plain",
				json: "application/json",
				default: "application/octet-stream"
			}
		}
	}
})()

